import 'dart:convert';
import 'package:http/http.dart' as http;

import 'package:logger/logger.dart';

class AuthApi {
  static const baseUrl = 'http://localhost:8080';
  static final logger = Logger();

  // 注册用户
  static Future<String> registerUser({
    required String username,
    required String email,
  }) async {
    final response = await http.post(
      Uri.parse('$baseUrl/api/auth/register/submit'),
      headers: {'Content-Type': 'application/json'},
      body: jsonEncode({
        'username': username,
        'email': email,
      }),
    );
    logger.i("*********response***********");
    logger.i(response.body);
    logger.i("*********response***********");

    if (response.statusCode == 200) {
      return response.body;
    } else {
      throw Exception('注册失败: ${response.reasonPhrase}');
    }
  }

  // 验证注册验证码
  static Future<String> verifyRegisterCode(int code) async {
    var uri = Uri.parse('$baseUrl/api/auth/register/verify');
    final response = await http.post(
      uri,
      headers: {'Content-Type': 'application/json'},
      body: jsonEncode({'code': code}),
    );
    logger.i("验证码验证请求: ${response.statusCode}");

    if (response.statusCode == 200) {
      return response.body;
    } else {
      throw Exception('验证码验证失败: ${response.reasonPhrase}');
    }
  }

  // 用户登录
  static Future<String> login(String identifier) async {
    final response = await http.post(
      Uri.parse('$baseUrl/api/auth/login/submit?identifier=$identifier'),
      headers: {'Content-Type': 'application/json'},
    );
    logger.i("登录请求: ${response.statusCode}");

    if (response.statusCode == 200) {
      return response.body;
    } else {
      throw Exception('登录请求失败: ${response.reasonPhrase}');
    }
  }

  // 验证登录验证码
  static Future<Map<String, dynamic>> verifyLoginCode(int code) async {
    final response = await http.post(
      Uri.parse('$baseUrl/api/auth/login/verify'),
      headers: {'Content-Type': 'application/json'},
      body: jsonEncode({'code': code}),
    );

    if (response.statusCode == 200) {
      return jsonDecode(response.body);
    } else {
      throw Exception('登录验证失败: ${response.reasonPhrase}');
    }
  }

  // 用户登出
  static Future<String> logout() async {
    final response = await http.get(
      Uri.parse('$baseUrl/api/auth/logout'),
      headers: {'Content-Type': 'application/json'},
    );

    if (response.statusCode == 200) {
      return response.body;
    } else {
      throw Exception('登出失败: ${response.reasonPhrase}');
    }
  }
}
